package com.sj.purchase.manager;

import com.alibaba.fastjson.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by yangrd on 2017/7/22.
 */
@Component
public class SkuInfoManager {

    @Value("${sj.darwin.sku}")
    private String api;

    @Autowired
    private RestTemplate restTemplate;

    private static Map<String, SkuInfo> skuInfoMap;

    private static final SkuInfo DEFAULT_SKU_INFO = new SkuInfo();

    public SkuInfo getSkuInfo(String skuNo) {
        if (skuInfoMap == null) {
            synchronized (SkuInfoManager.class) {
                if (skuInfoMap == null) {
                    initSkuInfo();
                }
            }
        }
        return skuInfoMap.getOrDefault(skuNo, DEFAULT_SKU_INFO);
    }

    public void initSkuInfo() {
        String jsonStr = restTemplate.getForObject(api, String.class);
        skuInfoMap = JSONArray.parseArray(jsonStr, SkuInfo.class).stream().collect(Collectors.toMap(SkuInfo::getSkucode, o -> o));
    }


}
